const logger = require('../util/log');
const helloController = require('./hello');
const opusController = require('./opus')
const device = require('../util/device')
const audioCodec = require('../lib/audio')

const TAG = 'CONTROLLER';

async function handleClient(socket, request, msg, isBinary) {
    const DeviceId = device.getDeviceId(request);
    const ClientId = device.getClientId(request);
    const ip = request.socket.remoteAddress;

    if (!DeviceId || !ClientId) {
        logger.log(TAG, `Invalid client: IP(${ip}), ${device.getReqIDs(request)}`)
        return;
    }

    if (isBinary){
        await handleBinary(socket, request, msg);
    } else {
        await handleMsg(socket, request, msg);
    }
}

async function handleBinary(socket, request, buffer) {
    // console.log(`opus data come, ${device.getReqIDs(request)}, length: ${buffer.length}`)
    const DeviceId = device.getDeviceId(request);
    const ClientId = device.getClientId(request);
    audioCodec.parseAudioData(DeviceId, ClientId, buffer);
}

async function handleMsg(socket, request, msg){
    const ip = request.socket.remoteAddress;

    try {
        const event = JSON.parse(msg);
        dispatch(socket, request, event);
    } catch (e) {
        console.error(e);
        const msgLine = `Invalid msg: IP(${ip}), ${device.getReqIDs(request)}`
        logger.log(TAG, msgLine)
    }
}

function dispatch(socket, request, event){
    switch (event.type) {
        case 'hello':
            helloController.handleHello(socket, request, event);
            break;
        case 'listen':
            opusController.handleOPUS(socket, request, event);
            break;
    }
}

module.exports = {
    handleClient,
}